<template>
  <div>
    <div style="margin-top: 140px">
      <el-row>
        <el-col :span="8">
          <div class="f-m-l-5" >
            <el-descriptions title="对局信息" :column="2" size="medium">
              <el-descriptions-item label="白方">{{ gameInfo.white }}</el-descriptions-item>
              <el-descriptions-item label="白方ELO">{{ gameInfo.whiteElo }}</el-descriptions-item>
              <el-descriptions-item label="黑方">{{ gameInfo.black }}</el-descriptions-item>
              <el-descriptions-item label="黑方ELO">{{ gameInfo.blackElo }}</el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="1" size="medium">
              <el-descriptions-item label="结果">{{ gameInfo.result }}</el-descriptions-item>
              <el-descriptions-item label="开局">{{ gameInfo.opening }}</el-descriptions-item>
              <el-descriptions-item label="赛事">{{ gameInfo.event }}</el-descriptions-item>
              <el-descriptions-item label="类型">{{ gameInfo.type }}</el-descriptions-item>
              <el-descriptions-item label="限时">{{ gameInfo.time }}</el-descriptions-item>
              <el-descriptions-item label="对局时间">{{ gameInfo.gameDate }}</el-descriptions-item>
              <el-descriptions-item label="链接">{{ lichessGameUrl + gameInfo.hash }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
        <el-col :span="8">
          <el-row>
            <chessboard :onPromotion="promote" :orientation="boardColor" @onMove="getLearnBoardInfo"
                        :fen="exerciseFen" :style="{opacity: isBoss ? 0.05 : 1 }" />
          </el-row>

          <el-descriptions :column="2" size="medium">
            <el-descriptions-item label="用时">{{ timeText }}</el-descriptions-item>
            <el-descriptions-item label="平均每题">{{ (secondCount / questionCount).toFixed(1)  }}秒</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="8">
          <el-descriptions  title="习题信息" :column="1" size="medium">

          </el-descriptions>
          <el-descriptions  :column="2" size="medium">
            <el-descriptions-item label="行棋方">{{ colorText }}</el-descriptions-item>
            <el-descriptions-item label="分差">{{ gameData?.value }}</el-descriptions-item>

          </el-descriptions>
          <el-descriptions :column="3" size="medium">

            <el-descriptions-item label="练习次数">{{ Number(gameData?.correct || 0) + Number(gameData?.wrong || 0) }}</el-descriptions-item>
            <el-descriptions-item label="成功">{{ gameData?.correct || 0}}</el-descriptions-item>
            <el-descriptions-item label="失败">{{ gameData?.wrong || 0}}</el-descriptions-item>

          </el-descriptions>
          <el-descriptions :column="3" size="medium">
            <el-descriptions-item label="总次数">{{ totalCorrect + totalWrong}}</el-descriptions-item>
            <el-descriptions-item label="总成功">{{ totalCorrect || 0}}</el-descriptions-item>
            <el-descriptions-item label="总失败">{{ totalWrong }}</el-descriptions-item>
          </el-descriptions>



          <el-descriptions :column="1" size="medium">
            <el-descriptions-item label="分析">{{ gameData?.analyzed || '否'}}</el-descriptions-item>
            <el-descriptions-item label="禁用">{{ gameData?.disabled || '否'}}</el-descriptions-item>
          </el-descriptions>

          <el-tooltip class="item" effect="dark" content="展示或者隐藏答案，未答对过则算作答错一次" placement="top">
            <el-button size="mini" round icon="el-icon-document-checked"
                       :type="!showAnswer ? 'success' : 'warning'"  @click="showAnswerHandler"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="跳转下一题，练习模式下未作答则算作失败一次" placement="top">
            <el-button  size="mini" round icon="el-icon-arrow-right" type="primary" @click="nextQuestion"></el-button>
          </el-tooltip>


          <el-tooltip class="item" effect="dark" content="开启后仅在一次就答对的情况下自动跳转下一题" placement="top">
            <el-switch
                v-model="autoNext"
                active-text="自动下一题"
                class="f-m-5"
                >
            </el-switch>
          </el-tooltip>

<!--          返回退出按钮-->
          <el-button class="item" style="margin-left: 140px"
                     v-loading.fullscreen.lock="fullscreenLoading" type="danger" round  size="mini" icon="el-icon-circle-close" :loading=autoLoading @click="back2ExerciseList"></el-button>

          <div v-if="showAnswer">
            <el-descriptions :column="3" size="medium">
              <el-descriptions-item label="错着">{{ gameData.badMove }}</el-descriptions-item>
              <el-descriptions-item label="正着">{{ gameData.correctMove }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>

import {hex2str, invoke, parseFenDropHistory} from "@/lib/utils";
import * as utils from "@/lib/utils";
import {chessboard} from 'vue-chessboard'
import Database from "@/lib/database";
import {lichessGameUrl} from "@/lib/constants";
import moment from "moment/moment";
import emitvue from "@/lib/emitvue";
import Chessmate from "@/lib/chessmate";
import _ from "lodash";


export default {
  name: "ExerciseBoard",
  data() {
    return {
      fullscreenLoading: false,
      exerciseFen: utils.newGame,
      backFen: [],
      isBoss: false,
      isDev: false,
      boardColor: 'white',
      colorText: '白方',
      gameInfo: {},
      lichessGameUrl: lichessGameUrl,
      showAnswer: false,
      autoLoading: false,
      badFen: '',
      correctFen: '',
      undoFlag: false,
      questionList: [],
      gameData: null,
      successFlag: false,
      noFail: null, // null-未开始，true-一次成功，false-失败过
      autoNext: false,
      timer: null,
      // 总的答对答错情况
      totalCorrect: 0,
      totalWrong: 0,
      questionCount: 0,
      secondCount: 0,
      timeText: '',

    }
  },
  methods: {
    async getLearnBoardInfo(data) {
      if (data.history?.length) {
        // 判断习题
        this.exerciseFen = parseFenDropHistory(data.fen)
        if (this.successFlag) {
          await utils.sleep(500)
          this.exerciseFen = this.backFen
          return this.$notify({duration: 1000, title: '通知', message: "已经回答过本题", type: 'success'})
        }
        if (this.exerciseFen === this.correctFen) {
          if (this.noFail !== false) this.noFail = true
          // 一次成功且没有看过答案 才能算成功
          if (this.noFail) {
            this.successFlag = true
            this.totalCorrect ++
            await Database.recordExerciseResult(this.gameInfo.hash, this.gameInfo.fenHash, 1)
            this.$notify({duration: 1000, title: '通知', message: "回答正确", type: 'success'})
          } else {
            this.$notify({duration: 1000, title: '通知', message: "在答错之后回答正确", type: 'success'})
          }
        } else if (this.exerciseFen === this.badFen) {
          this.noFail = false
          await Database.recordExerciseResult(this.gameInfo.hash, this.gameInfo.fenHash, -1)
          this.$notify({duration: 1000, title: '通知', message: "你选择了对局时的错误走法", type: 'error'})
          this.totalWrong ++
        } else {
          this.noFail = false
          await Database.recordExerciseResult(this.gameInfo.hash, this.gameInfo.fenHash, -1)
          this.$notify({duration: 1000, title: '通知', message: "回答错误", type: 'warning'})
          this.totalWrong ++
        }
        await utils.sleep(500)
        // 更新对错等数据
        const res = await Database.getSingleExercise(this.gameData.hash, this.gameData.fenHash, this.gameData.moveNum)
        this.gameData.wrong = res[0].wrong
        this.gameData.correct = res[0].correct
        this.exerciseFen = this.backFen
        // 没有失败过，或者点了查看答案，再选择就直接下一题
        if ((this.noFail || this.showAnswer) && this.autoNext) {
          await this.pickQuestion()
        }
      }
    },
    // 升变
    promote() {
      if (confirm("是否升变为后？")) {
        return 'q'
      } else {
        if (confirm("是否升变为车？")) {
          return 'r'
        } else {
          if (confirm("是否升变为马？")) {
            return 'n'
          } else {
            if (confirm("是否升变为象？")) {
              return 'b'
            }
          }
        }
      }
      return 'q'
    },
    async getGameInfo() {
      const res = await Database.getGameInfoByHash(this.gameData.hash)
      this.gameInfo = res
      this.gameInfo.fenHash = hex2str(this.gameData.fenHash)
      this.gameInfo.gameDate = moment(Number(this.gameInfo.gameDate)).format('YYYY-MM-DD HH:mm:ss')
    },
    back2ExerciseList() {
      emitvue.$emit("back2ExerciseList")
    },
    async enterSingleExercise() {
      await this.getGameInfo()
      this.exerciseFen = hex2str(this.gameData.fenHash)
      this.fillData()
    },
    fillData() {
      this.backFen = this.exerciseFen
      this.colorText = Chessmate.isWhite(this.exerciseFen) ? '白方' : '黑方'
      this.boardColor = Chessmate.isWhite(this.exerciseFen) ? 'white' : 'black'
      this.badFen = Chessmate.move(this.exerciseFen, this.gameData.badMove)
      this.correctFen = Chessmate.move(this.exerciseFen, this.gameData.correctMove)
    },
    // 抽取一道题
    async pickQuestion() {
      this.questionCount ++
      const randomNum = utils.getRandom(this.questionList.length)
      const single = _.cloneDeep(this.questionList[randomNum])
      this.questionList.splice(randomNum, 1)
      await this.fillOneSingleData(single)
    },
    async fillOneSingleData(single) {
      this.gameData = single
      this.gameData.disabled = this.gameData.disabled === '1' ? '是' : '否'
      this.gameData.analyzed = this.gameData.analyzed === '1' ? '是' : '否'
      const questionInfo = await Database.getGameInfoByHash(single.hash)
      this.gameInfo = questionInfo
      this.gameInfo.fenHash = hex2str(this.gameData.fenHash)
      this.exerciseFen = hex2str(this.gameData.fenHash)
      this.fillData()
      this.noFail = null
      this.successFlag = false
      this.showAnswer = false
      this.gameInfo.gameDate = moment(Number(this.gameInfo.gameDate)).format('YYYY-MM-DD HH:mm:ss')
    },
    // 跳转下一题
    async nextQuestion() {
      this.showAnswer = false
      // 答题模式
      if (this.questionList.length > 0) {
        if (this.noFail === null) {
          // 没有答题算做错一次
          await Database.recordExerciseResult(this.gameInfo.hash, this.gameInfo.fenHash, -1)
          this.totalWrong++
        }
        await this.pickQuestion()
      } else {
        const res = await Database.getOneExerciseForLearn(this.cond || {})
        const single = res.data?.[0]
        if (!single) return this.$notify({duration: 1000, title: '通知', message: "已经是最后一题了", type: 'success'})
        await this.fillOneSingleData(single)
        this.questionCount ++
      }
    },
    // 控制显示答案逻辑
    async showAnswerHandler() {
      this.showAnswer = !this.showAnswer
      if (this.showAnswer === true) {
        if (this.noFail === null) {
          // 没有答题算做错一次
          await Database.recordExerciseResult(this.gameInfo.hash, this.gameInfo.fenHash, -1)
          this.noFail = false
        }
      }
    }
  },
  async mounted() {
    this.isDev = location.protocol.indexOf('http') !== -1
    // 如果是开发模式，默认走老板键
    const isHome = await invoke('isHome', null)
    if (isHome === 'true' || isHome === true) {

    } else {
      this.isBoss = this.isDev
    }

    if (this.type === 'allExercise') {
      this.fullscreenLoading = true
      const res = await Database.getExerciseForLearn(this.cond)
      const { data } = res
      this.questionList = data
      await this.pickQuestion()
      this.fullscreenLoading = false
      this.$notify({duration: 1000, title: '通知', message: "习题加载完成", type: 'success'})
    } else {
      this.gameData = this.data
      await this.enterSingleExercise()
    }
    this.timer = setInterval(()=>{
    this.secondCount++
      console.log("this.secondCount", this.secondCount)
    }, 1000)
  },
  components: {
    chessboard,
  },
  destroyed() {
    clearInterval(this.timer)
  },
  props: {
    data: {
      correct: 0,
      wrong: 0,
      analyze: 0,
      disabled: 0,
    },
    type: null,
    cond: null,
  },
  watch: {
    secondCount(now) {
      this.timeText = utils.getDateTextBySecond(now)
    },
  }
}
</script>


<style scoped>

</style>